<template>
  <div class="table">
    <div class="topBtn">
      <!-- <span>活动配置条件</span> -->
      <el-button type="primary" size="small" @click="openSelectShop"
        >添加配置</el-button
      >
    </div>
    <el-table :data="conditionListTable" border style="width: 100%">
      <el-table-column prop="config_id" align="center" label="序号" width="60">
      </el-table-column>
      <el-table-column prop="name" align="center" width="auto" label="配置名称">
      </el-table-column>
      <el-table-column
        prop="item_name"
        align="center"
        width="auto"
        label="活动名称"
      >
      </el-table-column>
      <el-table-column prop="ratio" align="center" width="100" label="抽奖概率">
      </el-table-column>
      <el-table-column prop="sort" align="center" width="100" label="排序">
      </el-table-column>
      <el-table-column prop="prize_name" width="auto" label="奖品名称">
      </el-table-column>
      <el-table-column prop="code" width="auto" align="center" label="奖品图">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.prize_img"
            style="width: 80px; height: 80px"
            :src="scope.row.prize_img"
            :preview-src-list="[scope.row.prize_img]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="prize_stock"
        align="center"
        width="100"
        label="库存"
      >
      </el-table-column>
      <!-- <el-table-column
                prop="created_at"
                label="配置时间">
            </el-table-column> -->
      <el-table-column width="280" align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            v-if="typeSub == 13"
            size="mini"
            @click="addNamelist(scope.row)"
            >录入中奖名单</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="editCondition(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            @click="delCondition(scope.row.config_id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 添加条件弹框 -->
    <el-dialog
      title="添加配置"
      @closed="closedFn"
      width="45%"
      :visible.sync="dialogVisible"
    >
      <div class="itemBox">
        <span>配置名称：</span>
        <el-input v-model="namePrize"></el-input>
      </div>
      <div class="itemBox">
        <span>抽奖概率：</span>
        <el-input type="number" v-model="ratioPrize"></el-input>
      </div>
      <div class="itemBox">
        <span>排序：</span>
        <el-input type="number" v-model="sortPrize"></el-input>
      </div>
      <div class="itemBox">
        <span>数量：</span>
        <el-input type="number" v-model="quantity"></el-input>
      </div>
      <div class="itemBox" style="display: flex">
        <span>配置图：</span>
        <div>
          <el-upload
            action="/api/client/base/uploadfile"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            ref="upload"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="true"
            :limit="1"
            :headers="myHeaders"
            :file-list="fileList"
            accept="image/jpeg, image/jpg, image/gif, image/png"
            :multiple="false"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisibleImg">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </div>
      </div>
      <div class="openBox" style="width: 90%">
        <span>选择奖券：</span>
        <div style="width: 100%">
          <div
            style="display: flex; justify-content: flex-end; margin-bottom: 5px"
          >
            <el-input
              style="width: 100%"
              v-model="searchPrize"
              placeholder="请输入奖券名称"
              clearable
              @input="clearPrizeFn"
            ></el-input>
            <el-button type="primary" size="small" @click="searchPrizeFn"
              >搜索</el-button
            >
          </div>
          <el-table
            border
            :data="goodsList"
            style="width: 100%; margin: 10px 0"
          >
            <el-table-column align="center" width="50">
              <template slot-scope="scope">
                <el-radio v-model="shopId" :label="scope.row.id">{{
                  ""
                }}</el-radio>
              </template>
            </el-table-column>
            <el-table-column
              prop="date"
              align="center"
              label="奖券主图"
              width="80"
            >
              <template slot-scope="scope">
                <img
                  style="width: 30px; height: 30px"
                  :src="scope.row.img"
                  alt=""
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              align="center"
              label="奖券名称"
              width="auto"
            >
            </el-table-column>
            <el-table-column
              prop="stock"
              align="center"
              label="库存"
              width="auto"
            >
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChangePrize"
            @current-change="handleCurrentChangePrize"
            :current-page="pagePrize"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pagesizePrize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalPrize"
            background
          >
          </el-pagination>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="selectShop">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 录入中奖名单 -->
    <el-dialog
      title="录入中奖名单"
      :visible.sync="dialogVisibleName"
      width="45%"
      @close="closeNameFn"
    >
      <el-form>
        <el-form-item label="活动名称" label-width="120px">
          {{ activityName }}
        </el-form-item>
        <el-form-item label="奖品名称" label-width="120px">
          {{ prizeName }}
        </el-form-item>
        <el-form-item label="中奖等级" label-width="120px">
          <el-input
            style="width: 50%"
            type="number"
            placeholder="请输入中奖等级"
            v-model="level"
          ></el-input>
          （1 = 一等奖 以此类推）
        </el-form-item>
        <el-form-item label="中奖用户手机号" label-width="120px">
          <el-input
            style="width: 50%"
            type="number"
            placeholder="请输入用户手机号搜索"
            v-model="phone"
          ></el-input>
          <el-button style="margin-left: 10px" @click="addNumber" size="medium"
            >搜索</el-button
          >
        </el-form-item>
        <el-form-item label-width="120px">
          <el-tag
            v-for="(item, index) in phoneList"
            :key="index"
            @close="closeTag(index)"
            style="margin-right: 10px"
            size="medium"
            closable
            >{{ item.nickname }}-{{ item.mobile }}</el-tag
          >
        </el-form-item>
        <el-form-item label="中奖时间" label-width="120px">
          <el-date-picker v-model="time" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <el-dialog
        title="用户搜索列表"
        :visible.sync="dialogVisibleInner"
        append-to-body
        width="40%"
        @close="closeInnerFn"
      >
        <div>
          <!-- <div style="display:flex;justify-content: flex-end;margin-bottom:5px;">
                <el-input v-model="searchShop" placeholder="请输入商品名称" clearable @input="clearShopFn"></el-input>
                <el-button type="primary" size="small" @click="searchShopFn">搜索</el-button>
              </div> -->
          <el-table border :data="userList" style="width: 100%; margin: 20px 0">
            <el-table-column align="center" width="50">
              <template slot-scope="scope">
                <el-radio v-model="userId" :label="scope.row.id">{{
                  ""
                }}</el-radio>
              </template>
            </el-table-column>
            <el-table-column
              prop="date"
              align="center"
              label="用户头像"
              width="80"
            >
              <template slot-scope="scope">
                <img
                  style="width: 30px; height: 30px"
                  :src="scope.row.headimg"
                  alt=""
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="nickname"
              align="center"
              label="用户昵称"
              width="auto"
            >
            </el-table-column>
            <el-table-column
              prop="mobile"
              align="center"
              label="用户手机"
              width="auto"
            >
            </el-table-column>
          </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleInner = false">取 消</el-button>
          <el-button type="primary" @click="addUserSubmit">确 定</el-button>
        </span>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleName = false">取 消</el-button>
        <el-button type="primary" @click="addNameSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    typeSub: {
      type: Number,
      default: "",
    },
    activityId: {
      type: String,
      default: "",
    },
    activityItemId: {
      type: String,
      default: "",
    },
    relId: {
      type: String,
      default: "",
    },
    marketId: {
      type: Number,
      default: "",
    },
  },
  data() {
    return {
      page: 1,
      pagesize: 10,
      total: 0,
      conditionListTable: [],
      conditionList: [],

      input: "",

      dialogVisible: false,

      shopId: "",
      goodsList: [],

      namePrize: "",
      ratioPrize: "",
      sortPrize: "",
      quantity: "",

      fileList: [], //配置图
      dialogVisibleImg: false,
      dialogImageUrl: "",
      myHeaders: {
        "access-token": this.$store.state.token, //这里重新定义了请求头
        Authorization: this.$store.state.token,
        "user-id": this.$store.state.user_id,
      },

      // checkList:[]

      configId: "",

      pagePrize: 1,
      pagesizePrize: 5,
      totalPrize: 0,
      searchPrize: "",

      // 录入中奖名单
      dialogVisibleName: false,
      level: "",
      phone: "",
      phoneList: [],
      time: "",
      activityName: "",
      prizeName: "",
      prizeId: null,

      dialogVisibleInner: false,
      userList: [],
      userId: "",
    };
  },
  watch: {},
  methods: {
    // 获取子活动配置列表
    getShopList() {
      let params = {
        name: this.input,
        activity_item_id: this.activityItemId,
        page: this.page,
        pagesize: this.pagesize,
      };
      this.$http
        .post("/api/root/activity/son/config/list", params)
        .then((res) => {
          console.log(res, "子活动配置列表");
          if (res.code == 1) {
            this.conditionListTable = res.data.data ? res.data.data : [];
            this.total = res.data.count;
          }
        });
    },

    // 多选
    selectCheck() {
      console.log(this.checkList, "0000");
    },

    // 点击编辑
    editCondition(row) {
      console.log(row, "///");
      this.configId = row.config_id;
      this.namePrize = row.name;
      this.ratioPrize = row.ratio;
      this.shopId = row.prize_id;
      this.sortPrize = row.sort;
      this.quantity = row.quantity;
      this.dialogVisible = true;
      if (row.image) {
        let arr = [];
        arr.push({
          url: row.image,
          id: row.image_id,
        });
        this.fileList = arr;
      }
      this.getShopOkList();
    },

    // 打开选择商品对话框
    openSelectShop() {
      this.dialogVisible = true;
      this.getShopOkList();
    },

    // 对话框确定
    selectShop() {
      // if(!this.shopId){
      //     this.$message.warning('请选择奖券')
      //     return
      // }
      if (!this.namePrize) {
        this.$message.warning("请输入配置名称");
        return;
      }
      if (this.ratioPrize == "" && this.ratioPrize != 0) {
        this.$message.warning("请输入抽奖概率");
        return;
      }
      if (!this.quantity && this.quantity * 1 < 1) {
        this.$message.warning("请输入数量至少为1");
        return;
      }
      if (this.ratioPrize * 1 < 0 || this.ratioPrize * 1 > 100) {
        this.$message.warning("抽奖概率为0-100");
        return;
      }
      let imgArr = [];
      console.log(this.fileList, "配置图");
      this.fileList.map((item) => {
        if (item.response) {
          imgArr.push(item.response.data.id);
        } else {
          imgArr.push(item.id);
        }
      });

      console.log(this.activityItemId, "0-----");
      let param = {
        config_id: this.configId,
        activity_id: this.activityId,
        activity_item_id: this.activityItemId,
        sort: this.sortPrize,
        prize_id: this.shopId,
        name: this.namePrize,
        ratio: this.ratioPrize,
        quantity: this.quantity,
        image: imgArr.join(","),
      };
      let url = this.configId
        ? "/api/root/activity/son/config/edit"
        : "/api/root/activity/son/config/add";
      this.$http.post(url, param).then((res) => {
        console.log(res, "添加子活动配置");
        if (res.code == 1) {
          this.dialogVisible = false;
          this.$message.success(this.configId ? "修改成功" : "添加成功");
          this.getShopList();
        } else {
          this.$message.warning(res.msg);
        }
      });
    },

    // 加载更多
    // loadShop(){
    //     this.getShopOkList('load')
    // },

    // 获取可关联商品列表
    getShopOkList() {
      let params = {
        keyword: this.searchPrize,
        page: this.pagePrize,
        pagesize: this.pagesizePrize,
        market_id: this.marketId,
      };
      this.$http.post("/api/root/activity/prize/lists", params).then((res) => {
        console.log(res, "奖品列表");
        if (res.code == 1) {
          this.goodsList = res.data.data ? res.data.data : [];
          this.totalPrize = res.data.count;
        }
      });
    },
    // 搜索奖品
    searchPrizeFn() {
      this.pagePrize = 1;
      this.pagesizePrize = 5;
      this.getShopOkList();
    },
    // 清除搜索
    clearPrizeFn() {
      if (this.searchPrize == "") {
        this.pagePrize = 1;
        this.pagesizePrize = 5;
        this.getShopOkList();
      }
    },

    // 上传配置图
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handlePictureCardPreview(file) {
      console.log("file", file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file, fileList) {
      console.log("fileList", fileList);
      this.fileList = fileList;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 10MB!");
      }
      return isLt2M;
    },

    // 关闭对话框
    closedFn() {
      this.pagePrize = 1;
      this.pagesizePrize = 5;
      this.shopId = "";
      // this.checkList = [];
      this.sortPrize = "";
      this.namePrize = "";
      this.ratioPrize = "";
      this.configId = "";
      this.quantity = "";
    },

    // 删除关联商品
    delCondition(config_id) {
      this.$confirm("此操作将删除该配置, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let params = {
          config_id,
        };
        this.$http
          .post("/api/root/activity/son/config/del", params)
          .then((res) => {
            console.log(res);
            if (res.code == 1) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getShopList();
            } else {
              this.$message.warning(res.msg);
            }
          });
      });
    },

    // 点击录入中奖名单
    addNamelist(row) {
      this.activityName = row.item_name;
      this.prizeName = row.prize_name;
      this.prizeId = row.prize_id;
      console.log(row, "-----");
      this.dialogVisibleName = true;
    },
    // 点击中奖手机号添加按钮
    addNumber() {
      if (this.phone == "") {
        this.$message.warning("请输入中奖手机号码");
        return;
      }
      let tag = /^1\d{10}$/;
      if (!tag.test(this.phone)) {
        this.$message.warning("请填写正确的手机号");
        return;
      }
      this.dialogVisibleInner = true;
      this.getUserList();
      // let phonbeIndex = this.phoneList.findIndex(item=>item==this.phone)
      // if(phonbeIndex!=-1){
      //   this.$message.warning("已添加过该手机号");
      //   return
      // }
      // this.phoneList.push(this.phone)
      // this.phone = ''
    },
    // 添加用户对话框确定
    addUserSubmit() {
      if (!this.userId) {
        this.$message.warning("请选择中奖用户");
        return;
      }
      let userItem = this.userList.find((item) => {
        if (item.id == this.userId) {
          return item;
        }
      });
      let userIndex = this.phoneList.findIndex(
        (item) => item.id == this.userId
      );
      if (userIndex != -1) {
        this.$message.warning("已添加过该用户");
        return;
      }
      this.phoneList.push(userItem);
      this.dialogVisibleInner = false;
    },

    // 关闭添加用户对话框
    closeInnerFn() {
      this.userList = [];
      this.userId = "";
    },

    // 获取中奖用户列表
    getUserList() {
      this.$http
        .post("/api/root/user/search/mobile", { mobile: this.phone })
        .then((res) => {
          console.log(res, "用户列表");
          if (res.code == 1) {
            this.userList = res.data ? res.data : [];
          }
        });
    },

    // 关闭标签
    closeTag(index) {
      console.log(index);
      this.phoneList.splice(index, 1);
    },
    // 对话框确定
    addNameSubmit() {
      if (!this.phoneList.length) {
        this.$message.warning("请添加中奖用户");
        return;
      }
      let arr = [];
      this.phoneList.map((item) => {
        arr.push(item.id);
      });
      let time = this.$moment(this.time).format("yyyy-MM-DD");
      let params = {
        rel_id: this.relId,
        prize_id: this.prizeId,
        activity_no: this.activityItemId,
        level: this.level,
        luck_user_id: arr.join(","),
        time,
      };
      this.$http
        .post("/api/root/activity/son/config/namelist/save", params)
        .then((res) => {
          console.log(res, "录入中奖名单结果");
          if (res.code == 1) {
            if (res.data.length) {
              this.$message.warning(res.data[0]);
            } else {
              this.$message.success("录入成功");
              this.dialogVisibleName = false;
            }
          } else {
            this.$message.warning(res.msg);
          }
        });
    },
    // 关闭录入对话框
    closeNameFn() {
      this.activityName = "";
      this.prizeName = "";
      this.prizeId = "";
      this.level = "";
      this.phone = "";
      this.phoneList = [];
      this.time = "";
    },

    handleSizeChange(val) {
      this.page = 1;
      this.pagesize = val;
      this.getShopList();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getShopList();
    },

    handleSizeChangePrize(val) {
      this.pagePrize = 1;
      this.pagesizePrize = val;
      this.getShopOkList();
    },
    handleCurrentChangePrize(val) {
      this.pagePrize = val;
      this.getShopOkList();
    },
  },
};
</script>

<style lang="less">
.table {
  padding-bottom: 20px;
  .block {
    display: flex;
    justify-content: flex-end;
    padding-top: 20px;
  }
}
.topBtn {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  span {
    font-weight: 600;
    margin-right: 10px;
  }
}

.itemBox {
  margin: 15px 0;
  span {
    display: inline-block;
    width: 70px;
    text-align: right;
  }
  .el-input {
    width: 50%;
  }
}

.conditionBox {
  .item {
    display: flex;
    align-items: center;
    margin-top: 15px;
    .tit {
      width: 70px;
      text-align: right;
    }
    .el-input {
      width: 30%;
      margin-right: 10px;
    }
  }
}

.openBox {
  display: flex;
  span {
    flex-shrink: 0;
  }
  .el-radio-group {
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow: auto;
    height: 200px;
    .el-radio {
      margin: 10px 0;
    }
  }
  .el-checkbox-group {
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow: auto;
    height: 200px;
    .el-checkbox {
      margin: 10px 0;
    }
  }
}
</style>

